/* 
 * Modbus app for RTU.
 * Copyright (c) 2012  apleilx
 * All rights reserved.
 * no limite
 */

/* ----------------------- Platform includes --------------------------------*/
#define _MAPP_MODULE_
#include "mbapp.h"
#include "osObjects.h"                                          // RTOS object definitions

uint32_t mbAppCnt = 0;

/*****************************************************************************//*!
* @brief       Slave device handle.
*               
* @param   none
*
* @return  none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/

void ModbusTask(void const *argument) {
    osEvent mbEvent;
    
    
    mbInit(9600, MB_PAR_EVEN);
    mbModeSet(MB_RTU_MASTER);
    mbCmdBuffInit(MB_CMD_BUFF_SIZE, 8);
    mbSetSlaveAddr(2);

    mbDynaCmdReq(2, FUN_CODE_READ_INPUT, &RegInput[0].uVal, 0, 32);
    mbDynaCmdReq(2, FUN_CODE_READ_INPUT, &RegInput[0].uVal, 0, 33);
    mbDynaCmdReq(2, FUN_CODE_READ_INPUT, &RegInput[0].uVal, 0, 34);
    mbDynaCmdReq(2, FUN_CODE_READ_INPUT, &RegInput[0].uVal, 0, 35);

    mbStaticCmdSet(0, 2, FUN_CODE_READ_INPUT, &RegInput[0].uVal, 0, 16);

    RegDiscrete[2] = 0xFF;
    RegDiscrete[4] = 0xFF;
    RegDiscrete[6] = 0xFF;
    RegDiscrete[7] = 0xFF;
    RegDiscrete[8] = 0xFF;

    for (;;) {
        if (mbState.bits.MasterMode) {
            mbMasterPoll();
            mbEvent = osSignalWait(MODBUS_EVENT_RTU_TIMER, MMB_TIME_OUT_MS);
            
            if (MODBUS_EVENT_RTU_TIMER != mbEvent.value.signals) {
                mbRcvSt = MB_RX_TIMEOUT;
            }
            
            osDelay(2);
        } else {
            mbSlavePoll();

            mbEvent = osSignalWait(MODBUS_EVENT_RTU_TIMER, SMB_TIME_OUT_MS);
            if ( MODBUS_EVENT_RTU_TIMER != mbEvent.value.signals ) {
                mbRcvSt = MB_RX_TIMEOUT;
            } else {
                
            }
        }
        osDelay(2);
        mbAppCnt++;

        if (0 == (mbAppCnt & 0x0F)) {
            mbDynaCmdReq(2, FUN_CODE_READ_REG, &RegHolding[0], 0, 8);
            mbDynaCmdReq(2, FUN_CODE_READ_REG, &RegHolding[16], 16, 8);
        }

    }
}

/*****************************************************************************//*!
* @brief   modbus timeout
*               
* @param   none
*
* @return  none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/
void mbMasterTimeOutCnt(void) {

}

/*****************************************************************************//*!
* @brief   modbus timeout
*               
* @param   none
*
* @return  none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/
void mbSlaveTimeOutCnt(void) {
        /*
        if((0 != bPulse_10ms) && ( mbTimeOutCnt < ( SMB_TIME_OUT_MS / 10 ) ) )
            mbTimeOutCnt ++;
        */
}

